package com.dhwl.hsh.merchant.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dhwl.hsh.lib.bean.Address;
import com.dhwl.hsh.lib.bean.req.AddTaskReq;
import com.dhwl.hsh.lib.bean.resp.CarTypeResp;
import com.dhwl.hsh.lib.core.HshException;
import com.dhwl.hsh.merchant.R;
import com.dhwl.hsh.merchant.common.Constant;
import com.dhwl.hsh.merchant.presenter.AddTaskPresenter;
import com.dhwl.hsh.merchant.presenter.iview.IAddTaskView;
import com.dhwl.hsh.merchant.ui.adapter.TaskAddressAdapter;
import com.dhwl.hsh.merchant.ui.dialog.BillDialogFragment;
import com.dhwl.hsh.merchant.view.ScrollViewWithListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * 我要用车页面
 *
 * @author Derek.Kidd
 * @time 2016/4/25 10:00
 */
public class AddTaskActivity extends BaseActivity implements BillDialogFragment.BillInputListener, IAddTaskView {

    @Bind(R.id.scrollView_content)
    ScrollView scrollView;

    @Bind(R.id.listView_address)
    ScrollViewWithListView addressListView;

    @Bind(R.id.tv_transport_date)
    TextView tvTransportDate;

    @Bind(R.id.tv_transport_time_des)
    TextView tvTransportTimeDes;

    @Bind(R.id.layout_transport_time)
    RelativeLayout layoutTransportT;

    @Bind(R.id.btn_add_shipping_add)
    Button btnAddShippingAdd;

    @Bind(R.id.tv_choose_truck)
    TextView tvChooseTruck;
    @Bind(R.id.arrow_choose_car)
    ImageView arrowChooseCar;
    @Bind(R.id.layout_choose_car)
    RelativeLayout layoutChooseCar;

    @Bind(R.id.tv_bill_type)
    TextView tvBillType;
    @Bind(R.id.arrow_bill_type)
    ImageView arrowBillType;
    @Bind(R.id.layout_bill_type)
    RelativeLayout layoutBillType;
    @Bind(R.id.icon_extra_service)
    ImageView iconExtraService;
    @Bind(R.id.tv_extra_service)
    TextView tvExtraService;

    @Bind(R.id.btn_need_carry)
    Button btnNeedCarry;
    @Bind(R.id.btn_need_receipt)
    Button btnNeedReceipt;
    @Bind(R.id.btn_need_remittance)
    Button btnNeedRemittance;

    @Bind(R.id.tv_tip_for_driver)
    TextView tvTipForDriver;

    @Bind(R.id.layout_tip_for_driver)
    RelativeLayout layoutTipForDriver;


    @Bind(R.id.tv_words_for_driver)
    TextView tvWordsForDriver;

    @Bind(R.id.layout_words_for_driver)
    RelativeLayout layoutWordsForDriver;

    @Bind(R.id.tv_total_price)
    TextView tvTotalPrice;

    @Bind(R.id.btn_submit)
    Button btnSubmit;


    private List<Address> addressList;
    private TaskAddressAdapter taskAddressAdapter;

    /**
     * 计费方式
     */
    private int billType = Constant.Order.VALUE_BILL_TYPE_1;
    /**
     * 是否需要搬运
     */
    private boolean isNeedCarry = false;
    /**
     * 是否需要回单
     */
    private boolean isNeedReceipt = false;
    /**
     * 是否需要汇款
     */
    private boolean isNeedRemittance = false;

    AddTaskReq addTaskReq;

    AddTaskPresenter addTaskPresenter;


    /**
     * 一次任务总价
     */
    double totalPrice = 0.0;

    int billPrice = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_task;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setTitleContent(R.string.title_add_task);
        addressListView.setParentScrollView(scrollView);
    }

    @Override
    protected void initData() {
        addTaskPresenter = new AddTaskPresenter();
        addTaskPresenter.attachView(this);

        addTaskReq = new AddTaskReq();
        addTaskReq.setCostType(billType);

        addressList = new ArrayList<>();
        //初始化一个空的发货地和配送地
        Address startAdd = new Address();
        startAdd.setIndex(Constant.Order.VALUE_START_ADDRESS);
        Address endAdd = new Address();
        endAdd.setIndex(1);

        addressList.add(0, startAdd);
        addressList.add(1, endAdd);

        taskAddressAdapter = new TaskAddressAdapter(this, addressList);
        addressListView.setAdapter(taskAddressAdapter);

        switch (billType) {
            case Constant.Order.VALUE_BILL_TYPE_1:
                tvBillType.setText(R.string.tv_bill_type_1);
                break;
            case Constant.Order.VALUE_BILL_TYPE_2:
                tvBillType.setText(R.string.tv_bill_type_2);
                break;
            case Constant.Order.VALUE_BILL_TYPE_3:
                tvBillType.setText(R.string.tv_bill_type_1);
                break;
            case Constant.Order.VALUE_BILL_TYPE_4:
                tvBillType.setText(R.string.tv_bill_type_1);
                break;
        }
    }


    @OnItemClick(R.id.listView_address)
    public void onAddressClick(int position) {
        Intent intent = new Intent(this, AddAddressActivity.class);
        intent.putExtra(Constant.Order.KEY_SHIPPING_ADDRESS, (Parcelable) addressList.get(position));
        intent.putExtra(Constant.UserInfo.KEY_BILL_TYPE, billType);
        startActivityForResult(intent, Constant.Order.REQUEST_CODE_2);
    }


    @OnClick({R.id.layout_transport_time, R.id.btn_add_shipping_add, R.id.layout_choose_car, R.id.btn_need_carry, R.id.btn_need_receipt, R.id.btn_need_remittance, R.id.layout_tip_for_driver, R.id.layout_words_for_driver, R.id.btn_submit})
    public void onClick(View view) {

        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.layout_transport_time:
                intent.setClass(this, ChooseTimeActivity.class);
                startActivityForResult(intent, Constant.Order.REQUEST_CODE_1);
                break;
            case R.id.btn_add_shipping_add:
                intent.setClass(this, AddAddressActivity.class);
                //新增空的配送地对象
                Address endAdd = new Address();
                endAdd.setIndex(addressList.size());
                intent.putExtra(Constant.Order.KEY_SHIPPING_ADDRESS, (Parcelable) endAdd);
                intent.putExtra(Constant.UserInfo.KEY_BILL_TYPE, billType);
                startActivityForResult(intent, Constant.Order.REQUEST_CODE_3);
                break;
            case R.id.layout_choose_car:
                intent.setClass(this, ChooseTruckActivity.class);
                startActivityForResult(intent, Constant.Order.REQUEST_CODE_4);
                break;
            case R.id.layout_bill_type://计费方式
                if (billType == Constant.Order.VALUE_BILL_TYPE_1) {
                    break;
                }
                intent.setClass(this, BillSettingActivity.class);
                intent.putExtra(Constant.UserInfo.KEY_BILL_TYPE, billType);
                startActivityForResult(intent, Constant.Order.REQUEST_CODE_6);
                break;
            case R.id.btn_need_carry:
                isNeedCarry = !isNeedCarry;
                if (isNeedCarry) {
                    btnNeedCarry.setTextColor(getResources().getColor(R.color.color_ff9b1a));
                    btnNeedCarry.setBackgroundResource(R.drawable.bg_extra_service_checked);
                } else {
                    btnNeedCarry.setTextColor(getResources().getColor(R.color.tv_bbbbbb));
                    btnNeedCarry.setBackgroundResource(R.drawable.bg_extra_service_normal);
                }
                break;
            case R.id.btn_need_receipt:
                isNeedReceipt = !isNeedReceipt;
                if (isNeedReceipt) {
                    btnNeedReceipt.setTextColor(getResources().getColor(R.color.color_ff9b1a));
                    btnNeedReceipt.setBackgroundResource(R.drawable.bg_extra_service_checked);
                } else {
                    btnNeedReceipt.setTextColor(getResources().getColor(R.color.tv_bbbbbb));
                    btnNeedReceipt.setBackgroundResource(R.drawable.bg_extra_service_normal);
                }
                break;
            case R.id.btn_need_remittance:
                isNeedRemittance = !isNeedRemittance;
                if (isNeedRemittance) {
                    btnNeedRemittance.setTextColor(getResources().getColor(R.color.color_ff9b1a));
                    btnNeedRemittance.setBackgroundResource(R.drawable.bg_extra_service_checked);
                } else {
                    btnNeedRemittance.setTextColor(getResources().getColor(R.color.tv_bbbbbb));
                    btnNeedRemittance.setBackgroundResource(R.drawable.bg_extra_service_normal);
                }
                break;
            case R.id.layout_tip_for_driver:
                //添加小费对话框
                new BillDialogFragment().show(getFragmentManager(), "bill_dialog");

                break;
            case R.id.layout_words_for_driver:
                intent.setClass(this, AddWordsActivity.class);
                startActivityForResult(intent, Constant.Order.REQUEST_CODE_5);
                break;
            case R.id.btn_submit:
                //校验 1.用车时间
                if (TextUtils.isEmpty(addTaskReq.getJobUserDate()) || TextUtils.isEmpty(addTaskReq.getJobUserTime())) {
                    showToast("用车时间必须设置");
                    return;
                }
                //校验 2.发货地、配送地
                if (TextUtils.isEmpty(addressList.get(0).getPosiName()) || TextUtils.isEmpty(addressList.get(1).getPosiName())) {
                    showToast("发货地或配送地必须设置");
                    return;
                }
                //校验  3.所选车型
                if (TextUtils.isEmpty(addTaskReq.getJobCarType())) {
                    showToast("请选择车型");
                    return;
                }

                String jobCondition = (isNeedCarry ? "CAR" : "") + (isNeedReceipt ? "REC" : "") + (isNeedReceipt ? "PAY" : "");
                if (!jobCondition.isEmpty())
                    addTaskReq.setJobCondition(jobCondition);

                addTaskPresenter.addTask(addTaskReq);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case Constant.Order.REQUEST_CODE_1:
                    StringBuffer userCarParameters = new StringBuffer();

                    int shippingType = data.getIntExtra(Constant.Order.SHIPPING_TIME_TYPE_KEY, Constant.Order.SHIPPING_TIME_TYPE_DAY);
                    userCarParameters.append(shippingType);
                    userCarParameters.append("-");
                    //按天 的每周几
                    if (shippingType == Constant.Order.SHIPPING_TIME_TYPE_DAY) {
                        HashMap<Integer, Boolean> weeks = (HashMap) data.getSerializableExtra("weeks");
                        StringBuffer stringBuffer = new StringBuffer();
                        stringBuffer.append("每周");
                        String[] weekOfDays = {"一", "二", "三", "四", "五", "六", "日"};
                        for (int i = 1; i < 8; i++) {
                            if (weeks.get(i)) {
                                userCarParameters.append(i);
                                stringBuffer.append(weekOfDays[i - 1]);
                            }
                        }
                        stringBuffer.append("发货");
                        tvTransportTimeDes.setText(stringBuffer.toString());
                    }
                    //按频率的 的每隔几天
                    else if (shippingType == Constant.Order.SHIPPING_TIME_TYPE_PERIOD) {
                        int interval = data.getIntExtra("interval", 0);
                        tvTransportTimeDes.setText("每隔" + interval + "天发货");
                        userCarParameters.append(interval);
                    }

                    String startDate = data.getStringExtra("start_date");
                    tvTransportDate.setText(startDate);
                    String transformTime = data.getStringExtra("transform_time");

                    addTaskReq.setJobUserDate(startDate);
                    addTaskReq.setJobUserTime(transformTime);
                    addTaskReq.setUserCarParameters(userCarParameters.toString());
                    break;
                case Constant.Order.REQUEST_CODE_2:
                    //点击发货地配送地址
                    Address address = data.getParcelableExtra(Constant.Order.KEY_SHIPPING_ADDRESS);
                    addressList.set(address.getIndex(), address);
                    taskAddressAdapter.notifyDataSetChanged();

                    addTaskReq.setJobDestination(addressList);
                    // 获取并更新总价
                    if (verifyCostMoney()) {
                        addTaskPresenter.costMoney(addTaskReq);
                    }

                    break;
                case Constant.Order.REQUEST_CODE_3:
                    //新增空的配送地对象
                    Address newAddress = data.getParcelableExtra(Constant.Order.KEY_SHIPPING_ADDRESS);
                    addressList.add(newAddress);
                    taskAddressAdapter.notifyDataSetChanged();
                    break;
                case Constant.Order.REQUEST_CODE_4:
                    //获取车型
                    CarTypeResp carTypeResp = data.getParcelableExtra(Constant.Order.KEY_TRUCK_TYPE);

                    tvChooseTruck.setText(carTypeResp.getCartypeName());
                    addTaskReq.setJobCarType(carTypeResp.getCartypeId());

                    // 获取并更新总价
                    if (verifyCostMoney()) {
                        addTaskPresenter.costMoney(addTaskReq);
                    }
                    break;
                case Constant.Order.REQUEST_CODE_5:
                    String words = data.getStringExtra(Constant.Order.KEY_WORDS);
                    tvWordsForDriver.setText(words);
                    addTaskReq.setRemark(words);
                    break;
                case Constant.Order.REQUEST_CODE_6:
                    totalPrice = data.getDoubleExtra("shipping_price", 0.00);
                    updateTaskPrice();
                    addTaskReq.setCostPara1(totalPrice);
                    switch (billType) {
                        case Constant.Order.VALUE_BILL_TYPE_3:
                            double truckPrice = data.getDoubleExtra("truck_price", 0);//按货价计费：平均每车货物价格
                            double percent = data.getDoubleExtra("truck_percent", 0);//按货价计费：每车货价百分比
                            addTaskReq.setCostPara2(truckPrice);
                            addTaskReq.setCostPara3(percent);
                            break;
                        case Constant.Order.VALUE_BILL_TYPE_4:
                            // TODO: 2016/5/26
                            int unitType = data.getIntExtra("unit_type", 0);//按件数计费：0：件 1：立方
                            double unitPrice = data.getDoubleExtra("unit_price", 0);//按件数计费：作为运费的价格
                            int unitNum = data.getIntExtra("unit_num", 0);//按件数计费：总件数
                            addTaskReq.setCostPara4(unitPrice);
                            addTaskReq.setCostPara5(unitNum);
                            break;
                    }
                    break;
            }
        }
    }


    /**
     * 按里程计费时验证是否可以获取总价
     */
    boolean verifyCostMoney() {
        //1.验证计费方式
        if (billType != Constant.Order.VALUE_BILL_TYPE_1) {
            return false;
        }
        //2.验证发货地 配送地
        if (TextUtils.isEmpty(addressList.get(0).getPosiName()) || TextUtils.isEmpty(addressList.get(1).getPosiName())) {
            totalPrice = 0.0;
            updateTaskPrice();
            return false;
        }
        //3.验证用车类型是否已选
        if (TextUtils.isEmpty(addTaskReq.getJobCarType())) {
            totalPrice = 0.0;
            updateTaskPrice();
            return false;
        }
        return true;
    }

    /**
     * 更新任务总价
     */
    private void updateTaskPrice() {
        String result = String.format(getString(R.string.total_price), totalPrice + billPrice);
        tvTotalPrice.setText(result);
    }

    @Override
    public void onDialogSureClick(int bill) {

        billPrice = bill;

        tvTipForDriver.setText(billPrice + "元");
        addTaskReq.setJobBill(String.valueOf(billPrice));

        updateTaskPrice();
    }


    @Override
    public void onAddTaskFailure(HshException e) {

    }

    @Override
    public void onAddTaskSuccess(Object object) {
        showToast("任务发布成功");
        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        startActivity(intent);
    }

    @Override
    public void onCostMoneySuccess(double totalPrice) {
        this.totalPrice = totalPrice;
        updateTaskPrice();
    }

    @Override
    public void onCostMoneyFailure(HshException e) {

    }

}
